from django.shortcuts import render
from django.views.generic.base import View
from django.http import HttpResponseRedirect, JsonResponse
# Create your views here.
from apps.organizations.models import CourseOrg, City

from pure_pagination import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
from apps.users.models import UserProfile
from apps.organizations.forms import AddAskForm
from apps.operation.models import UserFavorite
from mxoling.settings import MEDIA_URL

class OrgDescView(View):
    def get(self, request, org_id, *args, **kwargs):
        current_page = "desc"
        course_org = CourseOrg.objects.get(id=int(org_id))
        course_org.click_nums += 1
        course_org.save()
        has_fav = False
        if request.user.is_authenticated:
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):
                has_fav = True

        return render(request, 'org-detail-desc.html', {
            "course_org": course_org,
            "current_page":current_page,
            "has_fav": has_fav,
        })

class OrgCourseView(View):
    def get(self, request, org_id, *args, **kwargs):
        current_page = "course"
        course_org = CourseOrg.objects.get(id=int(org_id))
        course_org.click_nums += 1
        course_org.save()
        has_fav = False
        if request.user.is_authenticated:
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):
                has_fav =  True
        all_course = course_org.course_set.all()
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        # 对课程机构数据进行分页
        p = Paginator(all_course, per_page=4, request=request)
        course = p.page(page)

        return render(request, 'org-detail-course.html', {
            "all_course": course,
            "course_org": course_org,
            "current_page":current_page,
            "has_fav": has_fav,
        })

class OrgTeacherView(View):
    def get(self, request, org_id, *args, **kwargs):
        current_page = "teacher"
        course_org = CourseOrg.objects.get(id=int(org_id))
        course_org.click_nums += 1
        course_org.save()
        has_fav = False
        if request.user.is_authenticated:
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):
                has_fav = True
        all_teacher = course_org.teacher_set.all()

        return render(request, 'org-detail-teachers.html', {
            "all_teacher": all_teacher,
            "course_org": course_org,
            "current_page":current_page,
            "has_fav": has_fav,
        })


class OrgHomeView(View):
    def get(self, request, org_id, *args, **kwargs):
        current_page = "home"
        course_org = CourseOrg.objects.get(id=int(org_id))
        course_org.click_nums += 1
        course_org.save()
        has_fav = False
        if request.user.is_authenticated:
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):
                has_fav = True
        all_courses = course_org.course_set.all()[:3]
        all_teacher = course_org.teacher_set.all()[:2]
        return render(request,'org-detail-homepage.html',{
            "all_courses": all_courses,
            "all_teacher": all_teacher,
            "course_org": course_org,
            "current_page": current_page,
            "has_fav": has_fav,
        })

class AddAskView(View):
    def post(self, request, *args, **kwargs):
        userask_form = AddAskForm(request.POST)
        if userask_form.is_valid():
            # 保存,立即执行
            userask_form.save(commit=True)
            return JsonResponse({
                'status': 'success'
            })
        else:
            return JsonResponse({
                'status': 'fail',
                'msg': '添加出错',
            })


class OrgView(View):

    def get(self, request, *args, **kwargs):
        all_org = CourseOrg.objects.all()
        all_citys = City.objects.all()
        keywords = request.GET.get('keywords', '')
        search_type = 'org'
        if keywords:
            all_org = all_org.filter(
                Q(name__icontains=keywords) | Q(desc__icontains=keywords) | Q(category__icontains=keywords))
        hot_org = all_org.order_by('-click_nums')[:3]

        # 通过课程机构进行筛选
        category = request.GET.get('ct', '')
        if category:
            all_org = all_org.filter(category=category)
        # 通过城市进行筛选
        city_id = request.GET.get('city', '')
        if city_id:
            # 判断是否为数字类型
            if city_id.isdigit():
                all_org = all_org.filter(city_id=int(city_id))

        # 对课程机构进行排序
        sort = request.GET.get('sort','')
        if sort == 'students':
            all_org = all_org.order_by('-students')
        if sort == 'courses':
            all_org = all_org.order_by('-course_nums')

        org_nums = all_org.count()
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        # 对课程机构数据进行分页
        p = Paginator(all_org, per_page=5, request=request)
        orgs = p.page(page)
        return render(request, 'org-list.html',{
            'all_orgs': orgs,
            'org_nums': org_nums,
            'all_citys': all_citys,
            'category': category,
            'city_id': city_id,
            'sort': sort,
            'hot_org': hot_org,
            'keywords': keywords,
            'search_type': search_type,
        })
